import { Component, OnInit } from '@angular/core';
import { User } from '../model/user';
import { UserService } from '../service/user.service';
import { Router } from '@angular/router';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Message } from 'primeng/components/common/api';
import { Result } from '../model/result';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {

  public user: User = new User();
  public mobile: string;
  public code: string;


  msgs: Message[] = [];
  constructor(public userService: UserService, public router: Router, public http: HttpClient) {
  }

  ngOnInit() {
    this.user.username = 'admin';
    this.user.password = '123456';
  }

  login() {
    this.http.post('/login', null,
      {
        params: new HttpParams()
          .set('username', this.user.username)
          .set('password', this.user.password)
          .set('remember-me', this.user['remember-me'])
          .set('code', this.code)
      }).subscribe((result: Result) => {
        if (result.error === '') {
          this.userService.currentUser = result.data['principal'];
          this.router.navigateByUrl('/');
        } else {
          this.userService.currentUser = null;
          this.msgs = [];
          this.msgs.push({ severity: 'error', summary: '登录失败!', detail: result.error });
        }
      });
  }


  forgetPassword() {
    this.router.navigateByUrl('/user/forgetpassword');
  }

  getSmsCode() {
    if (this.mobile.length !== 11) {
      this.msgs = [];
      this.msgs.push({ severity: 'info', summary: '手机号码必须是11位的' });
      return;
    }

    this.http.get('/code/sms?mobile=' + this.mobile).subscribe(result => {
      if (result['error'] === '') {
        this.msgs = [];
        this.msgs.push({ severity: 'info', summary: result['data'] });
      } else {
        this.msgs = [];
        this.msgs.push({ severity: 'error', summary: '获取短信验证码出错' });
      }
    });
  }

  smsLogin() {
    this.http.post('/authentication/sms', null,
      {
        params: new HttpParams()
          .set('mobile', this.mobile)
          .set('code', this.code)
      }).subscribe((result: Result) => {
        if (result.error === '') {
          this.userService.currentUser = result.data['principal'];
          this.router.navigateByUrl('/');
        } else {
          this.userService.currentUser = null;
          this.msgs = [];
          this.msgs.push({ severity: 'error', summary: '登录失败!', detail: result.error });
        }
      });
  }

  showGrowl() {
    this.msgs = [];
    this.msgs.push({ severity: 'error', summary: 'test', detail: 'test test detail' });
  }

  qqLogin() {
    this.http.get('/auth/qq').subscribe(result => {

    });
  }


}
